import React from 'react';
import { connect } from 'react-redux';
import { messages } from 'share/common';
import {
  Form,
  Input,
  Popover,
  Button,
  DatePicker,
  InputNumber,
  Select,
  Badge
} from 'antd';
import { chnNumChar } from 'containers/setting/new-workflow/utils';
import Selector from 'components/selector';
const FormItem = Form.Item;
const Option = Select.Option;
import Chooser from 'components/chooser';
import errorMessage from 'share/errorMessage';
import moment from 'moment/moment';
import 'styles/setting/workflow-config/new-workflow-config.scss';
import 'styles/setting/workflow-matrix/matrix-edit-condition.scss';
import workflowMatrixService from 'containers/setting/workflow-matrix/workflow-matrix.service';
import defaultExpenseTypeIcon from 'images/expense/default-expense-type.png';

const formItemLayout = {
  labelCol: { span: 6 },
  wrapperCol: { span: 14, offset: 1 },
};

const selectOptions = [{
  value: 3001,
  label: messages('request-4.key562')/*顺序*/
}, {
  value: 3002,
  label: messages('request-4.key563')/*并列*/
}];

class EditCondition extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      isShowLoading: true,
      configFp: [],
      configFunctionProfile: {},
      levelConfig: {},
      saveLoading: false,
      topPermission: '', levelCode: '', levelOrgId: '', defaultValue: {},
      matrixParams: {
        "approvalMatrixId": null,
        "levelCode": "",
        "levelOrgId": "",
        "visibleCompanyScope": 1,
        "visibleCompanyRelation": null,
        "name": "",
      },
      loading: false,
      approvalMatrixColumnsList: [],
    }
  }

  componentDidMount() {
    const { approvalMatrixRule } = this.props;
    let { approvalMatrixColumnsList } = this.props;
    let { matrixParams } = this.state;
    if (approvalMatrixRule && approvalMatrixRule.approvalMatrixRuleId) {
      matrixParams = approvalMatrixRule;
      // (record.matrixRuleCondition || []).map(condition => {
      //   name = item.messageKey === condition.messageKey ? condition.valueName : ''
      // });
      matrixParams.matrixRuleCondition.map(item => {
        let type = this.getType(item.messageKey);
        let labelAndValue = this.getLabelAndValue(type);
        if (labelAndValue) {
          let { labelKey, valueKey } = labelAndValue;
          matrixParams[item.messageKey] = [{ [labelKey]: item.valueName, [valueKey]: item.value }];
        } else if (type === 'list') {
          matrixParams[item.messageKey] = { key: item.value, label: item.valueName }
        } else {
          matrixParams[item.messageKey] = item.value
        }
      })
    }
    this.setState({
      matrixParams,
      approvalMatrixColumnsList: approvalMatrixColumnsList,
      isShowLoading: false
    })
  }

  //保存
  handleSave = e => {
    e.preventDefault();
    const { form, type } = this.props;
    const { matrixParams, approvalMatrixColumnsList } = this.state;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        const { head } = this.state;
        let params = Object.assign({}, head, matrixParams, values,);
        let matrixRuleCondition = [];
        approvalMatrixColumnsList.map(item => {
          if (params[item.messageKey]) {
            let type = this.getType(item.messageKey);
            let labelAndValue = this.getLabelAndValue(type);
            //处理编辑时chooser类型的数据为字符串
            if (labelAndValue && Array.isArray(params[item.messageKey])) {
              let { valueKey } = labelAndValue;
              params[item.messageKey] = !!params[item.messageKey].length ? params[item.messageKey][0][valueKey] : null;
            }
            //处理selector类型
            if (params[item.messageKey] && params[item.messageKey]['key']) {
              params[item.messageKey] = params[item.messageKey]['key']
            }
            matrixRuleCondition.push({ messageKey: item.messageKey, value: params[item.messageKey] })
          }
        });
        let nowParams = {
          approvalMatrixRuleId: (type !== 'copy' && params.approvalMatrixRuleId) || null,
          approvalMatrixId: this.props.approvalMatrixId,
          priority: params.priority,
          approverOID: params.approverOID[0].userOID,
          expiredDate: (params.expiredDate && params.expiredDate.format('YYYY-MM-DD')) || null,
          matrixRuleCondition,
        }
        this.setState({
          saveLoading: true,
        });
        workflowMatrixService.postMatrixDetailCondition(nowParams).then(res => {
          this.setState({ saveLoading: false });
          this.props.close(true);
        }).catch(e => {
          this.setState({ saveLoading: false });
          errorMessage(e.response)
        })

      }
    })
  };

  getExpenseTypeItem = () => {
    return {
      title: messages('request-4.key219')/*选择费用*/,//选择费用
      url: `/api/expense/type/by/setOfBooks`,
      searchForm: [
        {
          type: 'select',
          id: 'depth',
          label: messages('request-4.key67')/*类型*/,
          options: [
            { label: messages('request-4.key220')/*父类型*/, value: 1 },
            { label: messages('request-4.key221')/*子类型*/, value: 2 }
          ]
        },
        {
          type: 'input',
          id: 'code',
          label: messages('request-4.key222')/*费用编码*/
        },
        {
          type: 'input',
          id: 'name',
          label: messages('request-4.key223')/*费用名称*/
        },
        {
          type: 'select',
          id: 'parentId',
          label: messages('request-4.key224')/*所属父类型*/,
          options: [],
          getUrl: `/api/expense/type/by/setOfBooks?setOfBooksId=${this.props.setOfBooksId}&page=0&size=1000&depth=1`,
          labelKey: 'name',
          valueKey: 'id',
          method: 'get',
        }
        // options: fatherExpenseType
        ,
        {
          type: 'select',
          id: 'expenseTypeCategoryId',
          label: messages('request-4.key225')/*费用大类*/,
          options: [],
          getUrl: `/api/expense/types/category?setOfBooksId=${this.props.setOfBooksId}`,
          labelKey: 'name',
          valueKey: 'id',
          method: 'get',
        }],
      columns: [
        {
          title: 'Icon',//费用Icon
          dataIndex: 'iconURL',
          width: '10%',
          render: value => <div><img style={{ width: 30, height: 30 }} src={value}
                                     onError={e => e.target.src = defaultExpenseTypeIcon}/></div>
        },
        {
          title: messages('request-4.key222')/*费用编码*/,//费用编码
          dataIndex: 'code'
        },
        {
          title: messages('request-4.key223')/*费用名称*/,//费用名称
          dataIndex: 'name',
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        },
        {
          title: messages('request-4.key67')/*类型*//*类型*/,
          dataIndex: 'depth',
          render: value => value === 1 ? messages('request-4.key220')/*父类型*/ : messages('request-4.key221')/*子类型*/
        },
        {
          title: messages('common.column.status')/*状态*/,
          dataIndex: 'enabled',
          width: '10%',
          render: value => (
            <Badge status={value ? 'success' : 'error'}
                   text={value ? messages('request-4.key226')/*启用temp*/ : messages('request-4.key227')/*禁用temp*/}/>
          )
        }
      ],
      key: 'expenseTypeOID'
    }
  };

  getCostCenterItems = (costCenterOID) => {
    return {
      title: messages('request-4.key231')/*成本中心*/,//成本中心
      url: `/api/my/cost/center/items/${costCenterOID}`,
      //成本中心名称"成本中心项名称／经理／编号
      searchForm: [
        {
          type: 'input',
          id: 'name',
          label: `${messages('request-4.key232')/*成本中心名称*/}/${messages('request-4.key233')/*经理*/}/${messages('request-4.key234')/*编号*/}`
        }
      ],
      columns: [
        {
          title: messages('request-4.key235')/*成本中心代码*/,//成本中心代码
          dataIndex: 'code'
        },
        {
          title: messages('request-4.key232')/*成本中心名称*/,//成本中心名称
          dataIndex: 'name',
          render: value => {
            return <Popover placement="topLeft" content={value}>{value}</Popover>
          }
        }
      ],
      key: 'costCenterItemOID'
    }
  };

  handleChangeValue = (value, messageKey, valueKey) => {
    let { matrixParams } = this.state;
    matrixParams[messageKey] = value || null
    this.setState({
      matrixParams
    })
  };

  handleChangeAttr = (value, messageKey, valueKey) => {
    let { matrixParams } = this.state;
    matrixParams[messageKey] = (value && !!value.length ) ? value[0][valueKey] : null;
    this.setState({
      matrixParams
    })
  };

  getLabelAndValue = (type, costCenterOID) => {
    let chooserDataMap = {
      'company': {
        type: 'permission_company',
        valueKey: 'companyOID',
        labelKey: 'name'
      },
      'user': {
        type: 'user',
        valueKey: 'userOID',
        labelKey: 'fullName'
      },
      'department_group': {
        type: 'department_group',
        valueKey: 'deptGroupCode',
        labelKey: 'name'
      },
      'user_group': {
        type: 'user_group',
        valueKey: 'userGroupOID',
        labelKey: 'name',
      },
      'department_role': {
        type: 'department_role',
        valueKey: 'positionCode',
        labelKey: 'positionName',
      },
      'expense_type': {
        valueKey: 'expenseTypeOID',
        labelKey: 'name',
        selectorItem: this.getExpenseTypeItem(),
        extraParams: {
          setOfBooksId: this.props.setOfBooksId,
          enabled: true,
        },
      },
      'department': {
        type: 'department',
        valueKey: 'departmentOid',
        labelKey: 'name'
      },
      'cost_center': {
        type: 'cost_center_item',
        valueKey: 'costCenterItemOID',
        labelKey: 'name',
        selectorItem: this.getCostCenterItems(costCenterOID),
      }
    };
    return chooserDataMap[type]
  };

  getType = messageKey => {
    let type;
    switch(messageKey) {
      case 'default_applicant_company':
        type = 'company';
        break;
      case 'default_user_applicant':
      case 'default_user_direct_leadership':
        type = 'user';
        break;
      case 'default_user_group':
        type = 'user_group';
        break;
      case 'custom_form_department_group':
      case 'default_department_group':
        type = 'department_group';
        break;
      case 'default_user_department':
      case 'select_department':
        type = 'department';
        break;
      case 'default_department_role':
        type = 'department_role';
        break;
      case 'default_expense_type':
        type = 'expense_type';
        break;
      case 'default_user_post'://默认条件中的自定义列表
      case 'default_user_category':
      case 'default_user_sex':
      case 'default_user_level':
        type = 'list';
        break;

      case 'cost_center_dimension1':
      case 'cost_center_dimension2':
      case 'cost_center_dimension3':
      case 'cost_center_dimension4':
      case 'cost_center_dimension5':
      case 'cost_center_dimension6':
      case 'cost_center_dimension7':
        type = 'cost_center';
        break;

    }
    return type;
  };

  formatMessageKeyList = condition => {
    let type = this.getType(condition.messageKey), template;
    let { matrixParams } = this.state;
    let chooserData = this.getLabelAndValue(type, condition.costCenterOID);
    switch(condition.messageKey) {
      case 'default_amount_from':
      case 'default_amount_to':
        template = <InputNumber
          onChange={res=>this.onChangeNumber(condition.messageKey,res)}
          value={matrixParams[condition.messageKey]} placeholder={messages('request-4.key128')/*请输入temp2*/}
          max={9999999999.99}
          min={0.00}/>
        break;
      case 'default_user_post'://默认条件中的自定义列表
      case 'default_user_category':
      case 'default_user_sex':
      case 'default_user_level':
        let systemCustomEnumerationType = {
          'default_user_post': 1002,
          'default_user_category': 1001,//人员类型
          'default_user_sex': 1007,
          'default_user_level': 1008,
        };
        let selectorItem = {
          url: `/api/custom/enumeration/system/by/type?systemCustomEnumerationType=${systemCustomEnumerationType[condition.messageKey]}`,
          label: record => `${record.messageKey}`,
          key: 'value',
          listKey: 'values',
          offlineSearchMode: false
        };
        template =
          <Selector showSearch={false}
                    allowClear
                    value={matrixParams[condition.messageKey]}
                    onChange={value => this.handleChangeValue(value, condition.messageKey, 'value')}
                    selectorItem={selectorItem}/>
        break;
      case 'default_department_level':
      case 'custom_form_department_level':
        let list = Array.apply(null, { length: 10 }).map((item, index) =>
          ({ id: String(index + 1), name: chnNumChar[index] }));//部门层级
        template =
          <Select
            allowClear
            value={matrixParams[condition.messageKey]}
            onChange={value => this.handleChangeValue(value, condition.messageKey, 'id')}
            placeholder={messages('request-4.key444')/*请选择temp*/}>{list.map(item => <Option key={item.id}>{item.name}</Option>)}</Select>;
        break;
      case 'default_user_position':
        template =
          <Input
            value={matrixParams[condition.messageKey]}
            placeholder={messages('request-4.key128')/*请输入temp2*/}
            maxLength={100}
            onChange={e => this.handleChangeValue(e.target.value, condition.messageKey)}
          />
        break;
      default:
        template =
          <Input
            value={matrixParams[condition.messageKey]}
            placeholder={messages('request-4.key128')/*请输入temp2*/}
            onChange={e => this.handleChangeValue(e.target.value, condition.messageKey)}
          />
        break;
    }

    return chooserData ?
      <Chooser
        placeholder={messages('common.select')/*请选择*/}
        type={chooserData.type || null}
        labelKey={chooserData.labelKey}
        valueKey={chooserData.valueKey}
        listExtraParams={{
          roleType: 'TENANT',
          ...chooserData.extraParams
        }}
        value={matrixParams[condition.messageKey]}
        onChange={(value) => this.handleChangeAttr(value, condition.messageKey, chooserData.valueKey)}
        selectorItem={chooserData.selectorItem}
        showNumber={false}
        newline
        single
        showClear
        showDetail
      /> : template
  };

  onChangeNumber = (messageKey, res) => {
    let { matrixParams } = this.state;
    matrixParams[messageKey] = res || null;
    this.setState({
      matrixParams
    })
  }

  handleTimeChange = res => {
    let { matrixParams } =this.state;
    matrixParams.expiredDate = res ? res.format('YYYY-MM-DD') : null;
    this.setState({
      matrixParams
    })
  };

  render() {
    const { isShowLoading, saveLoading, loading, configFunctionProfile, matrixParams, approvalMatrixColumnsList, approvalMatrixRule } = this.state;
    const { getFieldDecorator } = this.props.form;
    return (
      <div className="matrix-edit-condition">
        { !isShowLoading && <Form className="new-form" onSubmit={this.handleSave}>
          <FormItem
            {...formItemLayout}
            label={messages('request-4.key250')/*优先级*/}>
            {getFieldDecorator('priority', {
              initialValue: matrixParams.priority || 1,
              rules: [{
                required: true,
                message: messages('common.please.input')/*请输入*/,
              }]
            })(
              <InputNumber precision={0} min={0} max={9999}/>
            )}
          </FormItem>
          <FormItem
            {...formItemLayout}
            label={messages('request-4.key589')/*有效期*/}>
            {getFieldDecorator('expiredDate', {
              initialValue: matrixParams.expiredDate ? moment(matrixParams.expiredDate) : null,
            })(
              <div>
                <DatePicker
                  onChange={this.handleTimeChange}
                  value={matrixParams.expiredDate ? moment(matrixParams.expiredDate) : null}
                />
              </div>
            )
            }
          </FormItem>
          <FormItem {...formItemLayout} label={messages('request-4.key391')/*审批人*/}>
            {getFieldDecorator('approverOID', {
              rules: [
                {
                  required: true,
                  message: messages('common.select')/*请选择*/ //请选择
                }
              ],
              initialValue: matrixParams.approvalMatrixRuleId ? [{
                  fullName: matrixParams.approverName,
                  userOID: matrixParams.approverOID
                }] : undefined
            })(
              <Chooser
                placeholder={messages('common.select')/*请选择*/}
                type='user'
                labelKey='fullName'
                valueKey='userOID'
                listExtraParams={{
                  roleType: 'TENANT',
                }}
                showNumber={false}
                newline
                single
                showDetail
              />
            )}
          </FormItem>
          {approvalMatrixColumnsList && !!approvalMatrixColumnsList.length &&
          <h3 className="module-name">
            {messages('request-4.key251')/*条件设置*/}
          </h3>}
          {approvalMatrixColumnsList && (approvalMatrixColumnsList || []).map((condition, index) => {
            return <FormItem key={condition.messageKey} {...formItemLayout} label={condition.name}>
              {this.formatMessageKeyList(condition)}
            </FormItem>
          })}
          <div className="footer-operate" style={{ backgroundColor: '#ffffff', left: '0px' }}>
            {!configFunctionProfile.readOnly && <Button
              type="primary"
              htmlType="submit"
              loading={saveLoading}
              style={{ margin: '0px 10px' }}
            >
              {messages('common.ok')/*确定*/}
            </Button>}
            <Button onClick={this.props.close}>{messages('common.cancel')/*取消*/}</Button>
          </div>
        </Form>}
      </div>
    )
  }
}

function mapStateToProps(state) {
  return {
    tenant: state.login.tenant,
    tenantMode: state.main.tenantMode,
    authPolicyAll: state.main.authPolicyAll,
    company: state.login.company,
    currentMenuPermission: state.main.currentMenuPermission,
  }
}
const wrappedEditCondition = Form.create()(EditCondition);
export default connect(mapStateToProps)(wrappedEditCondition);
